<template>
  <ContainerGroup
    class="dept-container"
    style="flex-direction: row; box-sizing: border-box; overflow: hidden"
  >
    <!-- 科室类型展示区域开始 -->
    <Container ref="container" class="dept-type" :height="height">
      <div class="title">核算单元</div>
      <el-table
        ref="table"
        :data="deptType"
        :header-cell-style="{ background: '#f3f6fb', borderColor: '#e7ecf8' }"
        highlight-current-row
        @row-click="rowClick"
      >
        <el-table-column align="center" prop="edCode" label="编码" />
        <el-table-column prop="edName" label="名称" />
      </el-table>
    </Container>

    <!-- 列表区域开始 -->
    <Container
      class="query-box"
      style="padding: 0; background: #f0f2f5"
      :height="height"
    >
      <!-- 查询 -->
      <Container style="margin-bottom: 12px">
        <FilterForm
          ref="filterForm"
          :noimmediate="true"
          :elements="queryForm"
          @reset="reset"
          @submit="handleSearch"
        />
      </Container>
      <Container
        class="rule-detail"
        style="height: calc(100% - 67px); overflow: hidden"
      >
        <!-- 功能按钮 -->
        <div class="button-bar">
          <Button icon="add" @click="addDetail">新增</Button>
        </div>
        <!-- 列表 -->
        <div class="table-box">
          <el-table
            v-loading="loading"
            height="calc(100% - 20px)"
            :data="tableData"
            default-expand-all
            border
            :tree-props="treeProps"
            :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }"
            :row-class-name="tableRowClassName"
            highlight-current-row
          >
            <el-table-column align="center" type="index" />
            <el-table-column label="科室编码" prop="deptCode">
              <!-- <template slot-scope="scope">
            <div class="text-btn" @click="handleDept(scope.row)">
              {{
                scope.row.deptCode === "AAAAAAAAAA"
                  ? "9999"
                  : scope.row.deptCode
              }}
            </div>
          </template> -->
            </el-table-column>
            <el-table-column prop="deptName" label="名称" width="300">
              <template slot-scope="scope">
                <h3
                  v-show="scope.row.parentCode == 1"
                  v-html="scope.row.deptName"
                />
                <div
                  v-show="scope.row.parentCode == 0"
                  v-html="scope.row.deptName"
                />
              </template>
            </el-table-column>
            <!-- <el-table-column prop="deptName" label="名称" width="300" /> -->
            <el-table-column
              align="center"
              prop="clinicalPropertyName"
              label="临床属性"
            />
            <el-table-column
              align="center"
              prop="deptTypeName"
              label="核算单元"
            />
            <el-table-column
              align="center"
              prop="deptPropertyName"
              label="科室属性"
            />
            <!-- <el-table-column align="center" prop="sysName" label="院区名称">
            <template slot-scope="scope">
              {{ scope.row.projectId === 1 ? "三香" : "浒关" }}
            </template>
          </el-table-column> -->
            <el-table-column
              align="center"
              prop="isDealingsBill"
              label="科室/部门"
            >
              <template slot-scope="scope">
                {{ scope.row.parentCode === "0" ? "部门" : "科室" }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="isDealingsBill"
              label="是否往来账"
            >
              <template slot-scope="scope">
                {{ scope.row.isCurrAccount === "0" ? "否" : "是" }}
              </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="是否启用" width="120">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.rowStatus"
                  active-color="#FFA712"
                  :active-value="'0'"
                  :inactive-value="'1'"
                  @change="switchUse(scope.row)"
                />
              </template>
            </el-table-column> -->
            <el-table-column align="center" label="操作" width="120">
              <template slot-scope="scope">
                <!-- <span class="edit-detail" @click="editDetail(scope.row)">修改</span> -->
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="编辑"
                  placement="top"
                >
                  <i
                    class="el-icon-edit-outline"
                    style="
                    padding-top: 4px;
                    font-size: 20px;
                    color: #207efa;
                    cursor: pointer;
                  "
                    @click="editDetail(scope.row)"
                  />
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="top"
                  style="margin-left: 10px"
                >
                  <i
                    class="el-icon-delete"
                    style="
                  padding-top: 4px;
                  font-size: 20px;
                  color: #207efa;
                  cursor: pointer;
                "
                    @click="handleDel(scope.row)"
                  />
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </Container>

      <!-- 分页 -->
      <!-- <Pagination
        :total="pageAttr.total"
        :page="pageAttr.currentPage"
        :page-size="pageAttr.pageSize"
        @pagation="pagationChange"
      /> -->
      <!-- 弹层区域开始 -->
      <Drawer
        :visible="showEidtVlidate"
        :title="drawerTitle"
        width="30%"
        :footer-btns="[
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
          {
            text: '确定',
            type: 'primary',
            trigger: 'okBtn',
          },
        ]"
        @cancel="drawClose"
        @okBtn="saveEidtRule"
      >
        <el-form
          ref="form"
          :model="form"
          label-width="120px"
          style="margin-top: 48px"
        >
          <el-form-item label="编号：">
            <el-input
              v-model="form.deptCode"
              :disabled="deptDisabled"
              clearable
              style="width: auto"
            />
          </el-form-item>
          <el-form-item label="名称：">
            <el-input v-model="form.deptName" clearable style="width: auto" />
          </el-form-item>
          <el-form-item label="临床属性：">
            <el-select v-model="form.clinicalPropertyId" clearable>
              <!-- <el-option :value="''" label="/" /> -->
              <el-option
                v-for="(item, index) in clinicalPropertyList"
                :key="index"
                :value="item.edCode + '/' + item.edName"
                :label="item.edName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="科室属性：">
            <el-select v-model="form.deptPropertyId" clearable>
              <el-option
                v-for="(item, index) in deptPropertyList"
                :key="index"
                :value="item.edCode + '/' + item.edName"
                :label="item.edName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="核算单元：">
            <el-select v-model="form.deptTypeId" clearable>
              <template v-for="(item, index) in deptTypeList">
                <el-option
                  v-if="item.edName"
                  :key="index"
                  :value="item.edCode + '/' + item.edName"
                  :label="item.edName"
                />
              </template>
            </el-select>
          </el-form-item>

          <el-form-item label="设置一级科室:">
            <el-checkbox-group v-model="form.parentCode" @change="bindCheck">
              <el-checkbox />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="设置末级节点:">
            <el-checkbox-group v-model="form.isLeaf">
              <el-checkbox />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="是否往来账：">
            <el-radio-group v-model="form.isCurrAccount">
              <el-radio :label="'1'">是</el-radio>
              <el-radio :label="'0'">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </Drawer>
      <!-- 弹层区域结束 -->
    </Container>
    <!-- 列表区域结束 -->
  </ContainerGroup>
</template>

<script>
import {
  getEnumDetailSource,
  getDepartmentSource,
  modifyDepartment,
  addDepartment,
  getDepartmentSourceWithOrganization,
  getDeptSelect,
  updateRowStatusById,
  deleteByIdKszd
} from '../../../utils/apis/accountingUnit/dept'
import { BasicParams } from '../../../utils/basicParams'
import projectId from '../../../utils/apis/projectId'
import { Dept } from '../../../utils/apis/dept'
import Container from '../../../components/Container.vue'

export default {
  // 核算科室
  name: 'Dept',
  components: { Container },
  data() {
    return {
      jie: true,
      loading: false,
      deptDisabled: false,
      // 分页参数
      // pageAttr: {
      //   pageSize: 20,
      //   currentPage: 1,
      //   total: 0
      // },
      // container高度
      height: 'fill',
      // 科室类型表单
      deptType: [],
      isEdit: false,
      treeProps: {
        children: 'childrens'
      },
      // 规则详情表单
      tableData: [],
      showEidtVlidate: false,
      drawerTitle: '',
      // 新增或编辑表单
      form: {
        id: '',
        deptCode: '',
        deptName: '',
        clinicalPropertyId: '', // 属性
        deptPropertyId: '', // 科室属性
        deptTypeId: '', // 科室类型
        projectId: '',
        parentCode: false,
        isCurrAccount: '',
        isLeaf: false
      },
      clinicalPropertyList: [],
      accountList: [],
      deptTypeList: [],
      deptPropertyList: [],
      yardList: [
        {
          name: '三香',
          value: 1
        },
        {
          name: '浒关',
          value: 2
        }
      ],
      // parentCascader: [],
      // parentCascaderProps: {
      //   value: 'deptCode',
      //   label: 'deptName',
      //   children: 'childrens',
      //   checkStrictly: true
      // }
      parentsList: [],
      isSearchiing: false,
      newParamList: {},
      // 查询表单参数
      queryForm: [
        {
          label: '科室编码',
          key: 'deptCode',
          type: 'Select',
          clearable: true,
          value: '',
          filterable: true,
          remote: true,
          remoteMethod: this.deptCodeFilter,
          itemLabel: 'deptCode',
          itemValue: 'deptCode',
          options: []
        },
        {
          label: '科室名称',
          key: 'deptName',
          type: 'Select',
          clearable: true,
          value: '',
          filterable: true,
          remote: true,
          remoteMethod: this.deptFilter,
          itemLabel: 'deptName',
          itemValue: 'deptName',
          options: []
        },
        {
          label: '关联状态',
          key: 'relation',
          type: 'Select',
          clearable: true,
          value: '',
          itemLabel: 'label',
          itemValue: 'value',
          options: [
            {
              label: '全部',
              value: ''
            },
            {
              label: '关联',
              value: '1'
            },
            {
              label: '未关联',
              value: '0'
            }
          ]
        },
        {
          label: '启用状态',
          key: 'rowStatus',
          type: 'Select',
          clearable: true,
          value: '',
          itemLabel: 'label',
          itemValue: 'value',
          options: [
            {
              label: '全部',
              value: ''
            },
            {
              label: '启用',
              value: '0'
            },
            {
              label: '未启用',
              value: '1'
            }
          ]
        }

      ],
      currentRow: {}
    }
  },
  created() {
    // this.ruleDetail = this.tableData.lcfw
    this.getData()
  },
  mounted() {
    this.initOne()
    this.inittwo()
    this.initThree()
    // this.getPojectText()
  },
  methods: {
    handleDel(row) {
      // 删除
      this.$confirm({
        title: '温馨提示',
        content: '您确定要删除该条数据?',
        okText: '确定',
        cancelText: '取消',
        okFn: () => {
          deleteByIdKszd({
            id: row.id
          }).then((res) => {
            if (res.data.code === 200) {
              this.$message.success('删除成功')
              this.getData()
            } else {
              this.$message.error('删除失败')
            }
          })
        },
        cancelFn: () => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        }
      })
    },
    switchUse(row) {
      const param = {
        id: row.id,
        rowStatus: row.rowStatus
      }
      updateRowStatusById(param).then((res) => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.rowClick(this.currentRow)
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    tableRowClassName({ row, rowIndex }) {
      if (!row.isRelation) {
        return 'warning-row'
      }
      return ''
    },
    deptCodeFilter(val) {
      getDeptSelect({
        projectId: 1,
        deptTypeId: this.currentRow.edCode ?? '',
        sysId: 'Cost',
        rowStatus: 0,
        deptCode: val
      }).then((res) => {
        if (res.data.code === 200) {
          this.queryForm[0].options = res.data.data || []
        }
      })
    },
    deptFilter(val) {
      getDeptSelect({
        projectId: 1,
        deptTypeId: this.currentRow.edCode ?? '',
        sysId: 'Cost',
        rowStatus: 0,
        deptName: val
      }).then((res) => {
        if (res.data.code === 200) {
          this.queryForm[1].options = res.data.data || []
        }
      })
    },
    // 新增按钮事件
    addDetail() {
      this.isEdit = false
      this.drawerTitle = '新增科室/部门'
      this.showDetail()
    },
    // 获取科室类型
    getPojectText() {
      const basicParams = new BasicParams()
      basicParams.edParentCode = 'BD_DepartCategory'
      getEnumDetailSource(basicParams).then((res) => {
        if (res.data.code === 200) {
          this.deptType = res.data.data
          let defaultRow = {}
          this.deptType.forEach((item) => {
            if (item.edExtraFirstCode === '1') {
              defaultRow = item
            }
          })
          this.currentRow = defaultRow
          this.$nextTick(() => {
            setTimeout(() => {
              this.rowClick(defaultRow)
            }, 50)
          })
        } else {
          this.loading = false
          this.$message.error(res.data.message)
        }
      })
    },

    //  临床属性
    initOne() {
      const basicParams = new BasicParams()
      basicParams.edParentCode = 'CLINIC_PRO'
      getEnumDetailSource(basicParams).then((res) => {
        if (res.data.code === 200) {
          this.clinicalPropertyList = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 科室属性
    inittwo() {
      const basicParams = new BasicParams()
      basicParams.edParentCode = 'BD_DeptProperty'
      getEnumDetailSource(basicParams).then((res) => {
        if (res.data.code === 200) {
          this.deptPropertyList = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 核算分类
    initThree() {
      const basicParams = new BasicParams()
      basicParams.edParentCode = 'BD_DepartCategory'
      getEnumDetailSource(basicParams).then((res) => {
        if (res.data.code === 200) {
          this.parentsList = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },

    getData() {
      const basicParams = new BasicParams()
      basicParams.edParentCode = 'BD_DepartCategory'
      basicParams.edExtraFirstCode = ''
      getEnumDetailSource(basicParams).then((res) => {
        if (res.data.code === 200) {
          const firstData = {
            childrenList: null,
            createdBy: '',
            createdOn: '',
            edCode: '',
            edEdId: 1,
            edExtraEighthCode: '',
            edExtraEighthDescription: '',
            edExtraFifthCode: '',
            edExtraFifthDescriptoin: '',
            edExtraFirstCode: '',
            edExtraFirstDescription: '',
            edExtraFourthCode: '',
            edExtraFourthDescriptoin: '',
            edExtraNinthCode: '',
            edExtraNinthDescription: '',
            edExtraSecondCode: '',
            edExtraSecondDescription: '',
            edExtraSeventhCode: '',
            edExtraSeventhDescription: '',
            edExtraSexthCode: '',
            edExtraSexthDescription: '',
            edExtraThirdCode: '',
            edExtraThirdDescription: '',
            edId: '',
            edName: '全部',
            edOrder: 0,
            edParentCode: 'BD_DepartCategory',
            isLike: null,
            remark: '',
            rowStatus: 0,
            updatedBy: '',
            updatedOn: ''
          }
          this.deptTypeList = JSON.parse(JSON.stringify(res.data.data))
          res.data.data.unshift(firstData)
          this.deptType = res.data.data
          this.$nextTick(() => {
            this.setFirstRowSelected()
          })
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    editDetail(row) {
      this.isEdit = true
      this.drawerTitle = '修改科室/部门'
      this.showDetail(row)
    },
    // deptFilter(val) {
    //   getParentCode({
    //     deptName: val
    //   }).then((res) => {
    //     if (res.data.code === 200) {
    //       if (res.data.data.length) {
    //         this.parentsList = res.data.data
    //       }
    //     } else {
    //       getParentCodeList().then((res) => {
    //         if (res.data.code === 200) {
    //           this.parentsList = res.data.data
    //         }
    //       })
    //     }
    //   })
    // },
    bindCheck() {
      if (this.form.parentCode === true) {
        this.form.clinicalPropertyId = ''
      }
    },
    showDetail(row) {
      if (this.isEdit) {
        const params = {
          projectId: projectId.project,
          id: row.id
        }
        getDepartmentSource(params).then((res) => {
          if (res.data.code === 200) {
            this.deptDisabled = true
            this.form.id = res.data.data[0].id
            this.form.deptCode = res.data.data[0].deptCode
            this.form.deptName = res.data.data[0].deptName
            this.form.clinicalPropertyId =
              res.data.data[0].clinicalPropertyId +
              '/' +
              res.data.data[0].clinicalPropertyName
            this.form.deptPropertyId =
              res.data.data[0].deptPropertyId +
              '/' +
              res.data.data[0].deptPropertyName
            this.form.deptTypeId =
              res.data.data[0].deptTypeId + '/' + res.data.data[0].deptTypeName
            this.form.projectId = res.data.data[0].projectId
            this.form.parentCode =
              res.data.data[0].parentCode !== '0'
            this.form.isLeaf = res.data.data[0].isLeaf === 1
            this.form.isCurrAccount = res.data.data[0].isCurrAccount
          } else {
            this.$message.error(res.data.message)
          }
        })
      } else {
        this.deptDisabled = false
        this.form.id = ''
        this.form.deptCode = ''
        this.form.deptName = ''
        this.form.clinicalPropertyId = ''
        this.form.deptPropertyId = ''
        this.form.deptTypeId = ''
        this.form.projectId = ''
        this.form.parentCode = false
        this.form.isLeaf = false
        this.form.isCurrAccount = '0'
      }
      this.showEidtVlidate = true
    },

    drawClose() {
      this.showEidtVlidate = false
    },
    saveEidtRule() {
      const dept = new Dept()
      dept.deptCode = this.form.deptCode
      dept.deptName = this.form.deptName
      dept.clinicalPropertyId = this.form.clinicalPropertyId.split('/')[0] // 属性
      dept.clinicalPropertyName = this.form.clinicalPropertyId.split('/')[1] // 属性name
      dept.deptPropertyId = this.form.deptPropertyId.split('/')[0] // 科室属性
      dept.deptPropertyName = this.form.deptPropertyId.split('/')[1] // 科室属性名称
      dept.deptTypeId = this.form.deptTypeId.split('/')[0] // 科室类型
      dept.deptTypeName = this.form.deptTypeId.split('/')[1] // 科室类型
      dept.projectId = projectId.project
      dept.parentCode = this.form.parentCode ? '1' : '0'
      dept.isCurrAccount = this.form.isCurrAccount
      dept.isLeaf = this.form.isLeaf ? 1 : 0
      if (this.isEdit) {
        dept.id = this.form.id
        modifyDepartment(dept).then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.showEidtVlidate = false
            this.getData()
          } else {
            this.$message.error(res.data.message)
          }
        })
      } else {
        dept.id = ''
        addDepartment(dept).then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.showEidtVlidate = false
            this.getData()
          } else {
            this.$message.error(res.data.message)
          }
        })
      }
    },
    // 获取页面数据
    _getData() {},
    // 分页事件
    pagationChange(payload) {
      this.pageAttr.currentPage = payload.page
      this.pageAttr.pageSize = payload.pageSize
      this._getData()
    },
    // 点击 table - row 触发
    rowClick(row) {
      this.currentRow = row
      this.loading = true
      // deptTypeId: row.edId,
      const params = {
        projectId: projectId.project,
        deptTypeId: row.edCode,
        sysId: 'Cost',
        rowStatus: this.newParamList.rowStatus,
        deptCode: this.newParamList.deptCode,
        deptName: this.newParamList.deptName
      }
      getDepartmentSourceWithOrganization(params).then((res) => {
        this.loading = false
        if (res.data.code === 200) {
          this.tableData = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 设置第一行选中
    setFirstRowSelected() {
      setTimeout(() => {
        this.$refs.table.setCurrentRow(this.$refs.table.data[0])
      }, 0)
      this.rowClick(this.deptType[0])
    },
    reset() {},
    handleSearch(data) {
      this.newParamList = data
      this.rowClick(this.currentRow)
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-table .warning-row {
    background-color: #fef0f0;
    color: #f56c6c;
  }
.query-box {
  flex: 1;
}
.dept-type {
  padding: 0 !important;
  flex: 0 0 240px;
  margin-right: 10px;
}
.rule-detail {
  padding: 0 !important;
  flex: 1;
}
.title {
  box-sizing: border-box;
  padding: 10px;
  width: 100%;
  background-color: #fefefe;
  // border-bottom: 1px solid #ccc;
}
.edit-detail {
  color: #4073ff;
  cursor: pointer;
}
.button-bar {
  height: 48px;
  width: 100%;
  display: flex;
  align-items: center;
  padding-left: 12px;
  Button:first-of-type {
    margin-right: 12px;
  }
}
.is-child {
  display: inline-block;
  padding-left: 12px;
}
.not-child {
  font-weight: bold;
}
.table-box {
  box-sizing: border-box;
  padding: 12px;
  height: calc(100% - 50px);
  overflow: hidden;
  // padding-top: 0;
}
/deep/ .dept-type .el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #217dfa;
  color: #fff;
}
/deep/ .el-table__body tr.current-row > td {
  background-color: #217dfa;
  color: #fff;
}
</style>
